package com.github.cyf.upload.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author chenyifan
 * @create 2025-05-22 13:45
 */
@Slf4j
public class FileMD5Util {

    public static String getFileMD5(File file) {
        String value = null;
        FileInputStream in = null;
        MappedByteBuffer byteBuffer = null;
        try {
            in = new FileInputStream(file);
            byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
            if (value.length() < 32) {
                value = "0" + value;
            }
        } catch (Exception e) {
            log.error("文件MD5计算异常", e);
        } finally {
            FileUtil.close(in, byteBuffer);
        }
        return value;
    }

    public static String getFileMD5(MultipartFile file) {
        String value = null;
        try {
            byte[] uploadBytes = file.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BigInteger bi = new BigInteger(1, md5.digest(uploadBytes));
            value = bi.toString(16);
            if (value.length() < 32) {
                value = "0" + value;
            }
        } catch (IOException | NoSuchAlgorithmException e) {
            log.error("文件MD5计算异常", e);
        }
        return value;
    }
}
